from socket import *
from threading import Thread
import logging
import time

from rpc_protocal import RpcProtocal

BUF_SIZE = 1024
PORT_SERVER = 8888

logging.basicConfig(level=logging.DEBUG, format="[%(asctime)s] %(levelname)s --> %(message)s")
LOG = logging.getLogger(__file__)

class RpcServer:  # (Thread)
    def __init__(self, port: int):
        # super().__init__()
        self.protocal = RpcProtocal()
        self.sock = socket()
        self.sock.bind(("0.0.0.0", port))
        self.sock.listen(8)
        self.sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)  # 打开reuse addr选项

        self.list_tid = []

    def request_parse(self):
        client, _ = self.sock.accept()
        self.new_thread()  # 递归创建新线程
        b_msg = client.recv(BUF_SIZE)
        return b_msg

    def response_action(self, msg):
        self.protocal.load(msg)
        str_cmd = self.protocal.cmd()
        eval(str_cmd)

    def service(self):
        msg_recv = self.request_parse()
        self.response_action(msg_recv)

    # def run(self):
    #     self.service()

    def new_thread(self):
        tid = Thread(target=self.service, args=())
        tid.start()
        self.list_tid.append(tid)

    def join_all(self):
        # 动态过程 ??
        for tid in self.list_tid:
            tid.join()

    def rpc_add(self, num0: int, num1: int):
        LOG.debug("Remote method called ...")
        nSum = num0 + num1
        LOG.info("Calculate a result: %d" % nSum)
        return nSum


if __name__ == "__main__":
    rpc_server = RpcServer(PORT_SERVER)
    # list_threading = []
    rpc_server.new_thread()

    rpc_server.join_all()
